package AdminService

import (
	"context"
	"database/sql"
	"gdshop-admin-go-api/app/request/BaseReq"
	"gdshop-admin-go-api/library/response"
	"gdshop-admin-go-api/library/tools"
	toolsDb "gdshop-admin-go-api/library/tools/db"
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	"strings"
	"time"
)

func Permmenu(ctx context.Context, req *BaseReq.I) *response.JsonResponse {
	cacheAdminId := gconv.String(req.AdminId)
	cacheDuration := g.Cfg().GetDuration("site.AdminCacheTimeout") * time.Second
	obj := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, req.TableName).Where(
		"id",
		req.AdminId,
	)
	res, err := obj.Cache(cacheDuration, "adminCache:model:"+cacheAdminId).One()
	if err != nil {
		if err != sql.ErrNoRows {
			// 非 结果为空
			return response.FailByRequestMessage(nil, err.Error())
		}
	}
	if res.IsEmpty() {
		return response.FailByRequestMessage(nil, "获取信息失败")
	}
	result := res.Map()
	// 取部门
	resCon, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "sys_department").Where(
		"id",
		result["dept_id"],
	).Fields("name").Cache(cacheDuration,
		"adminCache:depaName:"+cacheAdminId).Value()
	result["departmentName"] = resCon.String()

	fanhui := g.Map{}
	// 取出 权限
	var permsRes []gdb.Value
	// 如果是 amdin ，取出全部
	if result["account"] == "admin" {
		permsRes, err = toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "sys_menu").Where(
			"type = 2").Fields("perms").Array()
		if err != nil {
			return response.FailByRequestMessage(nil, err.Error())
		}
		// 取菜单
		resMenu, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "sys_menu").All()
		if err != nil {
			return response.FailByRequestMessage(nil, err.Error())
		}
		fanhui["menus"] = resMenu.List()
	} else {
		dbPrefix := g.Cfg().GetString("database.Prefix")
		permsRes, err = toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "sys_menu").As("sm").LeftJoin("sys_role_menu srm",
			"srm.menu_id = sm.id").Where(
			"sm.type = 2 AND srm.role_id IN (SELECT role_id FROM "+dbPrefix+"admin_role WHERE admin_id = ?)",
			req.AdminId).Fields("sm.perms").Cache(cacheDuration,
			"adminCache:perms:"+cacheAdminId,
		).Array()
		if err != nil {
			return response.FailByRequestMessage(nil, err.Error())
		}
		// 取菜单
		resMenu, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "sys_menu").As("sm").LeftJoin("sys_role_menu srm",
			"srm.menu_id = sm.id").Fields("sm.*").Where(
			"srm.role_id IN (SELECT role_id FROM "+dbPrefix+"admin_role WHERE admin_id = ?)",
			req.AdminId).Cache(cacheDuration, "adminCache:menu:"+cacheAdminId).All()
		if err != nil {
			return response.FailByRequestMessage(nil, err.Error())
		}
		fanhui["menus"] = resMenu.List()
	}
	// 整理权限列表
	permsTmp := gconv.SliceStr(permsRes)
	var perms []string
	for _, item := range permsTmp {
		if strings.Index(item, ",") > -1 {
			perms = append(perms, strings.Split(item, ",")...)
		} else {
			perms = append(perms, item)
		}
	}
	fanhui["perms"] = tools.RemoveDuplicatesAndEmpty(perms)

	return response.SuccessByRequestMessageData(nil, "成功", fanhui)
}
